// src/utils/cache.ts
import { FOLLOW_KEY, COLLECT_KEY } from '@/types/keys'

// ====== 读 ======
export const getCollectList = () : string[] => (uni.getStorageSync(COLLECT_KEY) || []) as string[]
export const getFollowList = () : string[] => (uni.getStorageSync(FOLLOW_KEY) || []) as string[]

// ====== 写 + 广播 ======
export const setCollectList = (list : string[]) => {
	uni.setStorageSync(COLLECT_KEY, list)
	uni.$emit('collect:change', list)
}
export const setFollowList = (list : string[]) => {
	uni.setStorageSync(FOLLOW_KEY, list)
	uni.$emit('follow:change', list)
}

export const toggleFollow = (barberId : string) : boolean => {
	let followList : string[] = uni.getStorageSync(FOLLOW_KEY) || [];
	const index = followList.indexOf(barberId);

	if (index > -1) {
		followList.splice(index, 1);
	} else {
		followList.push(barberId);
	}

	// 关键修复：调用 setFollowList 触发存储和广播
	setFollowList(followList);
	return index === -1; // 返回是否为关注状态
};

// 切换收藏状态（修改后）
export const toggleCollect = (barberId : string) : boolean => {
	let collectList : string[] = uni.getStorageSync(COLLECT_KEY) || [];
	const index = collectList.indexOf(barberId);

	if (index > -1) {
		collectList.splice(index, 1);
	} else {
		collectList.push(barberId);
	}

	// 关键修复：调用 setCollectList 触发存储和广播
	setCollectList(collectList);
	return index === -1; // 返回是否为收藏状态
};